package com.tool.emulator.apple2.runtime;

import com.tool.emulator.common.Util;
import com.tool.emulator.common.VirtualDevice;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class VirtualDeviceState {

	private Map<Object, Object> map = new HashMap<>();

	public void saveState(VirtualDevice vd) throws Exception {
		Class cls = vd.getClass();
		for (; ; ) {
			for (Field f : cls.getDeclaredFields()) {
				String name = Util.slKey(f);
				if (name != null) {
					f.setAccessible(true);
					map.put(name, f.get(vd));
				}
			}

			if (cls == VirtualDevice.class)
				break;
			cls = cls.getSuperclass();

		}
	}

	public void loadState(VirtualDevice vd) throws Exception {

		Class cls = vd.getClass();
		for (; ; ) {
			for (Field f : cls.getDeclaredFields()) {
				String name = Util.slKey(f);
				if (name != null && map.containsKey(name)) {
					f.setAccessible(true);
					Object val = map.get(name);
					f.set(vd, val);
				}
			}
			if (cls == VirtualDevice.class)
				break;
			cls = cls.getSuperclass();

		}
	}

}
